'use strice';

// 核心api: getDisplayMedia，使用方式和getUserMedia类似

(function() {
    const deskVideo = document.getElementById('deskVideo');
    deskVideo.width = 400;
    deskVideo.height = 300;

    // 抓取桌面
    const shareDesktop = () => {
        // 取流限制
        const mediaStreamConstrains = { video: true };
        // 获取桌面数据
        const getDeskStream = (stream) => {
            deskVideo.srcObject = stream;
        };
        const handleError = (error) => {
            console.log(error);
        };
        // 只有在PC下才能抓取桌面
        if(navigator.mediaDevices.getDisplayMedia()) {
            navigator.mediaDevices.getDisplayMedia(mediaStreamConstrains).then(getDeskStream).catch(handleError);
        }
    };
    document.getElementById('shareDesktop').addEventListener('click', shareDesktop);

    let buffer;
    let mediaRecorder;

    // 开始录制桌面
    const startRecord = () => {
        buffer = [];
        const options = { mimeType: 'video/webm;codecs=vp8' };
        const handleDataAvailable = e => {
            if(e?.data?.size > 0) {
                buffer.push(e.data);
            }
        };
        if(!MediaRecorder.isTypeSupported(options.mimeType)) {
            console.error(`${options.mimeType} is not supported!`);
            return
        }
        try {
            mediaRecorder = new MediaRecorder(deskVideo.srcObject, options);
        } catch (error) {
            console.error(`failed to create MediaRecorder: ${error}`);
        }
        mediaRecorder.addEventListener('dataavailable', handleDataAvailable);
        mediaRecorder.start(10);
    }
    document.getElementById('startRecord').addEventListener('click', startRecord);

    // 停止录制
    const stop = () => {
        if(mediaRecorder.state === 'recording') {
            mediaRecorder.stop();
            buffer = [];
        }
    }
    document.getElementById('stop').addEventListener('click', stop);

    // 下载录制好的视频
    const download = () => {
        const blob = new Blob(buffer, { type: 'video/webm' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.style.display = 'none';
        a.download = 'aaa.webm';
        a.click()
    }

    document.getElementById('download').addEventListener('click', download);
})()